#!/usr/bin/env python
# # -*- coding: utf-8 -*-

"""
@File:      doc2docx.py
@Author:    Jim.Dai.Cn
@Date:      2024/6/18 22:05
@Desc:         
"""

import os
import glob
# import comtypes.client
import tempfile, sys
from comtypes.client import CreateObject
import tkinter as tk
from tkinter import filedialog, messagebox
import shutil

# Create a GUI window to select input directory
root = tk.Tk()
root.withdraw()
input_dir = filedialog.askdirectory(title='Select Input Directory')

# Change backslashes to forward slashes in input directory
input_dir = input_dir.replace('\\', '/')

# Get list of .doc files in directory
doc_files = glob.glob(os.path.join(input_dir, '*.doc'))


# Define function to convert .doc to .docx
def doc_to_docx_win(doc_path, docx_path):

    # 指定目标文件夹和转换后文件的名称
    target_file_path = docx_path

    try:
        # 初始化COM库
        word = CreateObject('Word.Application')
        # 打开文档并设置为只读模式
        doc = word.Documents.Open(doc_path)
        # 保存为DOCX格式
        doc.SaveAs(target_file_path, FileFormat=16)  # Word.DocumentType.wdFormatXMLDocument
        print(f"文件已成功转换为: {docx_path}")
        # 关闭文档和Word应用
        doc.Close()
        word.Quit()
    except Exception as e:
        # 打印异常信息
        print(f"转换过程中出现错误: {e}")
        return None
    
    # # 检查转换后的文件是否存在
    # if os.path.exists(target_file_path):
    #     return target_file_path
    # else:
    #     return None
